const fs = require('fs');
const path = require('path');
const https = require('https');
const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();
const location = {
  host: "www.baidu.com",
  hostname: "www.baidu.com",
  href: "https://www.baidu.com/",
  origin: "https://www.baidu.com",
  pathname: "/",
  port: "",
  protocol: "https:",
}

async function proxySite(ctx) {
  // console.log('\n --------------------- \n');
  // console.log(ctx.request, '\n ======== \n');
  return new Promise(resolve => {
    https.get(location.href, {
      headers: {
        ...ctx.request.header,
        host: location.host,
      },
    }, res => {
      if (res.statusCode !== 200) {
        resolve([res.statusCode]);
        return;
      }
      let data = '';
      // res.setEncoding('utf-8');
      res.on('data', chunk => {
        data += chunk.toString();
        console.log(chunk.toString());
      });
      res.on('end', () => resolve([null, data]));
    }).on('error', err => resolve([err]));
  });
}

router.get('/', async (ctx, next) => {
  const [err, data] = await proxySite(ctx);
  fs.writeFileSync(path.join(__dirname, 'test.html'), data);
  // ctx.body = err || data;
  next();
});

app.use(router.routes());

app.listen(4000, () => console.log(`Server started ... ${4000}`));
